import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {FacilityMaintenanceRecord} from "@/types/resp/facilityMaintenanceRecord";
import facilityMaintenanceRecordApi from '@/api/facilityMaintenanceRecordApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import FacilityMaintenanceRecordAdd from "@/pages/facilityMaintenanceRecord/FacilityMaintenanceRecordAdd.tsx";
import FacilityMaintenanceRecordView from "@/pages/facilityMaintenanceRecord/FacilityMaintenanceRecordView.tsx";
import FacilitySelector from "@/pages/facility/FacilitySelector.tsx";
import StaffSelector from "@/pages/staff/StaffSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'



const FacilityMaintenanceRecordList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '公共设施保养记录列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<FacilityMaintenanceRecord[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<FacilityMaintenanceRecord>> = await facilityMaintenanceRecordApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<FacilityMaintenanceRecord> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<FacilityMaintenanceRecord>['columns'] = [
    {title: '公共设施名称', dataIndex: 'facilityName', key: 'facilityName'},
    {title: '保养开始时间', key: 'maintenanceStartDate', render: (_, record) => (
      <div>{record.maintenanceStartDate ? record.maintenanceStartDate.format('YYYY-MM-DD HH:mm:ss') : ''}</div>
    )},
    {title: '保养开始时间', key: 'maintenanceEndDate', render: (_, record) => (
      <div>{record.maintenanceEndDate ? record.maintenanceEndDate.format('YYYY-MM-DD HH:mm:ss') : ''}</div>
    )},
    {title: '维修保养人员', dataIndex: 'staffName', key: 'staffName'},
    {title: '备注', dataIndex: 'remark', key: 'remark'},
    {
      title: '操作',
      key: 'action',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [facilityMaintenanceRecordAddVisible, setFacilityMaintenanceRecordAddVisible] = useState(false);
  const [facilityMaintenanceRecordViewVisible, setFacilityMaintenanceRecordViewVisible] = useState(false);
  const [selectedFacilityMaintenanceRecordId, setSelectedFacilityMaintenanceRecordId] = useState(0)
  const [selectedFacilityMaintenanceRecord, setSelectedFacilityMaintenanceRecord] = useState({})

  const onAdd = () => {
    setSelectedFacilityMaintenanceRecordId(0)
    setFacilityMaintenanceRecordAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedFacilityMaintenanceRecordId(id)
    setFacilityMaintenanceRecordAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      facilityMaintenanceRecordApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: FacilityMaintenanceRecord) => {
    setSelectedFacilityMaintenanceRecord(record)
    setFacilityMaintenanceRecordViewVisible(true)
  };

  const [facilitySelectorVisible, setFacilitySelectorVisible] = useState(false);
  const findFacility = () => {
    setFacilitySelectorVisible(true);
  }
  const handleFacilitySelected = (selectedFacility: { facilityId?: number; facilityName?: string; }) => {
    setFacilitySelectorVisible(false)
    if (selectedFacility && 'facilityId' in selectedFacility) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      facilityId: selectedFacility['facilityId'],
      facilityName: selectedFacility['facilityName'],
      }));
    }
  };
  const handleCloseFacilitySelector = () => {
    setFacilitySelectorVisible(false)
  };
  const [staffSelectorVisible, setStaffSelectorVisible] = useState(false);
  const findStaff = () => {
    setStaffSelectorVisible(true);
  }
  const handleStaffSelected = (selectedStaff: { staffId?: number; staffName?: string; }) => {
    setStaffSelectorVisible(false)
    if (selectedStaff && 'staffId' in selectedStaff) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      staffId: selectedStaff['staffId'],
      staffName: selectedStaff['staffName'],
      }));
    }
  };
  const handleCloseStaffSelector = () => {
    setStaffSelectorVisible(false)
  };

  const handleCloseFacilityMaintenanceRecordAdd = () => {
    setFacilityMaintenanceRecordAddVisible(false)
  };

  const handleCloseFacilityMaintenanceRecordView = () => {
    setFacilityMaintenanceRecordViewVisible(false)
  };

  const onExport = () => {
    const headers = ['公共设施名称','保养开始时间','保养开始时间','维修保养人员','备注']
    facilityMaintenanceRecordApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.facilityName,d.maintenanceStartDate,d.maintenanceEndDate,d.staffName,d.remark])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="facilityMaintenanceRecordList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="facilityName" label="公共设施名称">
          <Input.Search placeholder="请选择公共设施名称" onSearch={findFacility} readOnly={true} />
        </Form.Item>
        <Form.Item name="staffName" label="维修保养人员">
          <Input.Search placeholder="请选择维修保养人员" onSearch={findStaff} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<FacilityMaintenanceRecord> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <FacilitySelector visible={facilitySelectorVisible} onFacilitySelected={handleFacilitySelected} onCloseFacilitySelector={handleCloseFacilitySelector} />
      <StaffSelector visible={staffSelectorVisible} onStaffSelected={handleStaffSelected} onCloseStaffSelector={handleCloseStaffSelector} />
      <FacilityMaintenanceRecordAdd visible={facilityMaintenanceRecordAddVisible} onCloseFacilityMaintenanceRecordAdd={handleCloseFacilityMaintenanceRecordAdd} id={selectedFacilityMaintenanceRecordId} />
      <FacilityMaintenanceRecordView visible={facilityMaintenanceRecordViewVisible} onCloseFacilityMaintenanceRecordView={handleCloseFacilityMaintenanceRecordView} viewRow={selectedFacilityMaintenanceRecord} />
    </div>
  );
};

export default FacilityMaintenanceRecordList;
